package com.yizhang.newfeatures;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 收集器
 */
public class CollectorTest {
    public static void main(String[] args) {
        List<Hero> list = List.of(
                new Hero("王二五", 20),
                new Hero("李四", 30),
                new Hero("张三", 20),
                new Hero("张三", 40)
        );

        // Map收集器
//        Map<String, Integer> map1 = list.stream().collect(Collectors.toMap(x -> x.name, x -> x.name.length()));

        // 分组后求重复个数
        Map<String, Long> map2 = list.stream().collect(Collectors.groupingBy(x -> x.name, Collectors.counting()));
        // 分组后求年龄和  下面2种一样
        Map<String, Integer> map3 = list.stream().collect(Collectors.groupingBy(x -> x.name, Collectors.summingInt(x -> x.age)));
        Map<String, Integer> map4 = list.stream().collect(Collectors.groupingBy(x -> x.name, Collectors.mapping(x -> x.age,
                Collectors.reducing(0, Integer::sum))));

//        for (Map.Entry<String, Integer> entry : map1.entrySet()) {
//            System.out.println(entry.getKey() + " : " + entry.getValue());
//        }
        for (Map.Entry<String, Long> entry : map2.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
        for (Map.Entry<String, Integer> entry : map3.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
        for (Map.Entry<String, Integer> entry : map4.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }

    public static class Hero {
        private String name;
        private int age;
        public Hero(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}
